package cn.itqiqi.student_system_java.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author kevin_琪琪
 * @version 1.0
 * @description java-jwt对称签名加密工具类
 * @date 2022-06-19 21:19
 */
public class JWTUtils {

    // 签名
    private static final String SIGNATURE = "token!@scv#$xcz%^z&*s()_+";

    /**
     * 生成token
     * @param map 传入payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        // 创建JWT
        JWTCreator.Builder builder = JWT.create();
        // 写入载荷
        map.forEach(builder::withClaim);
        // 设置时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        builder.withExpiresAt(instance.getTime());
        // 使用指定的密钥签名
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * 验证token
     * @param token 传入token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 获取token中payload
     * @param token 传入token
     * @return 返回token中 payload
     */
    public static DecodedJWT getTokenPayload(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}